import React, { useEffect } from 'react'
import { useImmer } from 'use-immer'
import Taro, { getCurrentInstance, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import qs from 'qs'
import { View, Text } from '@tarojs/components'
import { SpPage, SpSearch, SpFloatMenuItem, SpChat } from '@/components'
import { getDistributorId, entryLaunch } from '@/utils'
import { platformTemplateName } from '@/utils/platform'
import { useNavigation } from '@/hooks'
import req from '@/api/req'
import HomeWgts from '@/pages/home/comps/home-wgts'
import './custom-page.scss'

const initialState = {
  wgts: [],
  loading: true,
  shareInfo: null
}
function CustomPage(props) {
  const $instance = getCurrentInstance()
  const [state, setState] = useImmer(initialState)
  const { setNavigationBarTitle } = useNavigation()
  const { wgts, loading, shareInfo } = state

  useEffect(() => {
    fetch()
  }, [])

  const fetch = async () => {
    const { id } = await entryLaunch.getRouteParams($instance.router.params)
    const pathparams = qs.stringify({
      template_name: platformTemplateName,
      version: 'v1.0.1',
      page_name: `custom_${id}`,
      distributor_id: getDistributorId()
    })
    const url = `/pageparams/setting?${pathparams}`
    const { config, share } = await req.get(url)
    setState((draft) => {
      draft.wgts = config
      draft.loading = false
      draft.shareInfo = share
    })
    // setNavigationBarTitle(share?.page_name)
    // Taro.setNavigationBarTitle({
    //   title: share?.page_name
    // })
    // this.setState(
    //   {
    //     positionStatus: (fixSetting.length && fixSetting[0].params.config.fixTop) || false
    //   },
    //   () => {
    //     this.fetchInfo()
    //   }
    // )
  }

  useShareAppMessage(async (res) => {
    return getAppShareInfo()
  })

  useShareTimeline((res) => {
    return getAppShareInfo()
  })

  const getAppShareInfo = () => {
    const { id } = $instance.router.params
    const { userId } = Taro.getStorageSync('userinfo')
    const query = {
      id: id
    }
    if (userId) {
      query.uid = userId
      query.shareUserId = userId
      query.company_id = process.env.APP_COMPANY_ID
    }
    return {
      title: shareInfo.page_share_title,
      imageUrl: shareInfo.page_share_imageUrl,
      path: `/pages/custom/custom-page?${qs.stringify(query)}`,
      query: `${qs.stringify(query)}`
    }
  }

  const searchComp = wgts.find((wgt) => wgt.name == 'search')
  let filterWgts = []
  if (searchComp && searchComp.config.fixTop) {
    filterWgts = wgts.filter((wgt) => wgt.name !== 'search')
  } else {
    filterWgts = wgts
  }
  const fixedTop = searchComp && searchComp.config.fixTop
  const pageData = wgts.find((wgt) => wgt.name == 'page')
  return (
    <SpPage
      scrollToTopBtn
      className='page-custom-page'
      pageConfig={pageData?.base}
      loading={loading}
      title={shareInfo?.page_name}
      fixedTopContainer={fixedTop && <SpSearch info={searchComp} />}
      renderFloat={
        <View>
          <SpChat>
            <SpFloatMenuItem>
              <Text className='iconfont icon-headphones'></Text>
            </SpFloatMenuItem>
          </SpChat>
        </View>
      }
    >
      <HomeWgts wgts={filterWgts} />
    </SpPage>
  )
}

CustomPage.options = {
  addGlobalClass: true
}

export default CustomPage
